package com.csipsimple;

import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;

import com.csipsimple.api.ISipService;
import com.csipsimple.api.SipCallSession;
import com.csipsimple.api.SipManager;
import com.csipsimple.api.SipProfile;
import com.csipsimple.api.SipProfileState;
import com.csipsimple.service.SipService;
import com.csipsimple.utils.AccountListUtils;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.PreferencesProviderWrapper;

import static android.content.Context.BIND_AUTO_CREATE;

public class VoipUtil {

    private static String THIS_FILE = "VoipUtil";

    private static ISipService sipService;
    private static ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            sipService = ISipService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            sipService = null;
        }
    };

    /** 启动用户注册服务
     * @param mContext 启动安卓服务的Context, 比如某一个activity实列
     * @param username 用户的SIP账号用户名，也就是UnionID
     * @param password 用户的SIP账号密码
     * @param pvalid 注册有效期间隔，单位为秒
     */
    public static void startRegisterService(Context mContext, String username, String password, int pvalid){

        PreferencesProviderWrapper prefsWrapper = new PreferencesProviderWrapper(mContext);
        prefsWrapper.setPreferenceStringValue("ICE_ORANGE_SIP_USERNAME", username);
        prefsWrapper.setPreferenceStringValue("ICE_ORANGE_SIP_PASSWORD", password);
        Intent serviceIntent = new Intent(mContext, SipService.class);
        serviceIntent.putExtra("username", username);
        serviceIntent.putExtra("password", password);
        serviceIntent.putExtra("SIP_RESTART_SECONDS", pvalid);
        mContext.startService(serviceIntent);
        mContext.bindService(serviceIntent, connection, BIND_AUTO_CREATE);
    }

    public static void stopRegisterService() {
        if(sipService != null) {
            try {
                sipService.setAccountRegistration(1, 0);
                sipService.sipStop();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param mContext Contenxt，可使用getApplicationContext()
     * @return registerStatus
     *   UNREGISTERED   未注册
     *   REGISTERED 已注册
     *   REGISTERING 正在注册
     *   REGISTERING_ERROR 注册发生错误
     */
    public static String getRegisterStatus(Context context) {
        String status = "NOT_REGISTERED";

        SipProfileState accountInfo = null;
        Cursor c = context.getContentResolver().query(ContentUris.withAppendedId(SipProfile.ACCOUNT_STATUS_ID_URI_BASE, 1),
                null, null, null, null);
        if (c != null) {
            try {
                if(c.getCount() > 0) {
                    c.moveToFirst();
                    accountInfo = new SipProfileState(c);
                }
            } catch (Exception e) {
                Log.e(THIS_FILE, "Error on looping over sip profiles states", e);
            } finally {
                c.close();
            }
        }

        if (accountInfo != null && accountInfo.isActive()) {
            if (accountInfo.getAddedStatus() >= SipManager.SUCCESS) {

                status = "UNREGISTERED";
                if( TextUtils.isEmpty( accountInfo.getRegUri()) ) {
                    // Green
                    status = "REGISTERED";
                }else if (accountInfo.isAddedToStack()) {
                    String pjStat = accountInfo.getStatusText();	// Used only on error status message
                    int statusCode = accountInfo.getStatusCode();
                    if (statusCode == SipCallSession.StatusCode.OK) {
                        // Log.d(THIS_FILE,
                        // "Now account "+account.display_name+" has expires "+accountInfo.getExpires());
                        if (accountInfo.getExpires() > 0) {
                            // Green
                            status = "REGISTERED";
                        } else {
                            // Yellow unregistered
                            status = "UNREGISTERED";
                        }
                    } else if(statusCode != -1 ){
                        if (statusCode == SipCallSession.StatusCode.PROGRESS || statusCode == SipCallSession.StatusCode.TRYING) {
                            // Yellow progressing ...
                            status = "REGISTERING";
                        } else {
                            status = "REGISTERING_ERROR";
                        }
                    }else {
                        // Account is currently registering (added to pjsua but not replies yet from pjsua registration)
                        status = "REGISTERING";
                    }
                }
            } else {
                if(accountInfo.isAddedToStack()) {
                    status = "REGISTERING_ERROR";
                }else {
                    status = "REGISTERING";
                }
            }
        }
        return status;
    }
}
